<template>
    <TableView class="table">
        <template #form>
            <NSpace justify="space-between">
                <NSpace align="center">
                    资产名称:
                    <NInput style="width: 200rem" placeholder="请输入资产名称" v-model:value="paginationReactive.assetName"
                        clearable />
                    资产编号:
                    <NInput style="width: 200rem" placeholder="请输入资产编号" v-model:value="paginationReactive.assetNumber"
                        clearable />
                    资产类目:
                    <NTreeSelect style="width: 200rem" placeholder="请选择资产类目" v-model:value="paginationReactive.categoriesId"
                        clearable :options="categoryList" label-field="categoriesName" key-field="id"
                        children-field="childList" />
                    状态:
                    <NSelect style="width: 200rem" placeholder="请选择状态" v-model:value="paginationReactive.status" clearable
                        :options="[
                            { label: '未确认', value: '0' },
                            { label: '已确认', value: '1' }
                        ]" />
                    <NButton type="primary" style="width: 78rem" ghost
                        @click="() => ((paginationReactive.page = 1), getAssetsRequestList())">
                        查询
                    </NButton>
                </NSpace>
            </NSpace>
        </template>

        <template #table="props">
            <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
                :loading="tableLoading" />
        </template>

        <template #pagination>
            <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
                show-size-picker show-quick-jumper :suffix="() => '页'">
                <template #prefix>
                    <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </template>
    </TableView>

    <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
        <VDialogContent @close="modalVisible = false" @submit="handOver" title="提示">
            <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
                您确定点交吗？
            </div>
        </VDialogContent>
    </NModal>
</template>
<script setup lang="ts">
import { NSpace, NButton, NDataTable, NPagination, useMessage, NModal, NInput, NSelect, NTreeSelect } from 'naive-ui'
import { h, reactive, ref, watch, onDeactivated, onMounted } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useViewerStore } from '@/views/OA/Common/store'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisible = ref(false)

const columns: DataTableColumns = [
    {
        title: '申请人',
        key: 'userName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '资产编号',
        key: 'assetNumber',
        width: 80,
        align: useStore.isCenter
    },
    {
        title: '资产名称',
        key: 'assetName',
        width: 80,
        align: useStore.isCenter
    },
    {
        title: '资产类目',
        key: 'categoriesName',
        width: 80,
        align: useStore.isCenter
    },
    {
        title: '申请时间',
        key: 'createTime',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '类型',
        key: 'circulationType',
        width: 40,
        align: useStore.isCenter,
        render: ({ circulationType }) => {
            return circulationType == 'A0569' ? '领用' : circulationType == 'A0570' ? '归还' : '转移'
        }
    },
    {
        title: '点交时间',
        key: 'updateTime',
        width: 80,
        align: useStore.isCenter
    },
    {
        title: '点交状态',
        key: 'status',
        width: 40,
        align: useStore.isCenter,
        render: ({ status }) => {
            return status == '0' ? '未确认' : status == '1' ? '已确认' : '/'
        }
    },
    {
        title: '操作',
        key: 'action',
        align: useStore.isCenter,
        width: 40,
        fixed: 'right',
        render: (row: any) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    style: { display: row.status == '0' ? 'inline-block' : 'none' },
                    onClick: async () => {
                        handOverId.value = row.id
                        modalVisible.value = true
                    }
                },
                {
                    default: () => '点交'
                }
            )
        ]
    }
]
// 上一页下一页
const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    assetName: null, //资产名称
    assetNumber: null, //资产编号
    categoriesId: null, //资产类目
    status: null, //状态
    onChange: (page: number) => {
        paginationReactive.page = page
        getAssetsRequestList()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        getAssetsRequestList()
    }
})
// 点交
const handOverId = ref()
const handOver = async () => {
    modalVisible.value = false
    tableLoading.value = true
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'assetsReturnReceiveRequestSubmit',
        override: {
            params: {
                id: handOverId.value
            }
        }
    })
    if (error) return message.error('点交失败'), (tableLoading.value = false)
    if (res.code !== 0) return message.error('点交失败'), (tableLoading.value = false)
    getAssetsRequestList()
    message.success('点交成功')
}
// 获取类目下拉
const categoryList = ref<any>([])
const getCategoryList = async () => {
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getCategoryList'
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    categoryList.value = res.data
}
/**选择节点返回所有子节点id */
const getAllChildList = (data, val) => {
  if (!val) return val
  console.log('val: ', val)
  function getObjById(list, id) {
    if (!list instanceof Array) {
      return null
    }

    for (let i in list) {
      let item = list[i]
      if (item.id === id) {
        return item
      } else {
        if (item.childList) {
          let value = getObjById(item.childList, id)
          if (value) {
            return value
          }
        }
      }
    }
  }
  function getChildren(list, returnValue = [val]) {
    for (let i in list) {
      returnValue.push(list[i].id)
      if (list[i].childList) {
        getChildren(list[i].childList, returnValue)
      }
    }
    return returnValue
  }
  let obj = getObjById(data, val)
  if (obj && obj.childList) {
    let childrenList = getChildren(obj.childList)
    return childrenList
  } else return [val]
}
// 获取列表
const tableData: any = ref([])
const tableLoading = ref(false)
const getAssetsRequestList = async () => {
    tableLoading.value = true
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'assetsReturnReceiveRequestList',
        override: {
            data: {
                page: paginationReactive.page,
                limit: paginationReactive.pageSize,
                assetName: paginationReactive.assetName,
                assetNumber: paginationReactive.assetNumber,
                categoriesId: getAllChildList(categoryList.value, paginationReactive.categoriesId), // 资产类目
                status: paginationReactive.status
            }
        }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    tableData.value = []
    setTimeout(() => {
        tableData.value = res.data.list
        paginationReactive.itemCount = res.data.totalCount
    }, 0)
}

const keyUpDown = (e: any) => e.key == 'Enter' && getAssetsRequestList()
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
    () => route,
    async () => {
        if (route.path == '/OA/AssetsManegement/AssetsReturnReceiveRequest/AssetsReturnReceiveRequest') {
            getAssetsRequestList()
            window.addEventListener('keyup', keyUpDown, false)  // 回车
        }
    },
    { deep: true, immediate: true }
)

onMounted(() => getCategoryList())

</script>
<style scoped lang="scss">
.table {
    padding: 29rem 30rem 42rem;
}
</style>
      